---
import Layout from "#/layouts/Layout.astro"
import { ClientRouter } from "astro:transitions"
import MatrixCover from "../components/MatrixCover.astro"
import H1 from "../components/typography/h1.astro"
import TextP from "../components/typography/TextP.astro"

interface Props {
  title: any
  text: any
}

const { title, text } = Astro.props

const pathname = new URL(Astro.request.url).pathname
const currentPath = pathname.slice(1) // remove the first "/"
---

<head>
  <meta charset="utf-8" />
  <ClientRouter />
</head>

<Layout title="Union">
  <div
    class:list={[
      "header-grid place-self-center",
      currentPath === "" ? "header-grid--open" : "header-grid--collapsed",
    ]}
  >
    <div class="shiny-border">
      <div
        class="glow-effect"
        transition:persist
      >
      </div>
    </div>
    <MatrixCover />
    <div class="bg-gradient-to-r from-transparent via-black to-transparent px-4 py-6 text-center header-text-content flex justify-center overflow-hidden">
      <div class="max-w-2xl flex flex-col gap-4 slide-this">
        <H1>{title}</H1>
        <TextP>{text}</TextP>
      </div>
    </div>
  </div>
  <div transition:animate>
    <slot />
  </div>
</Layout>

<style
  lang="postcss"
  is:global
>
.header-grid {
    --outer-border: 16px;
    --inner-border: 2px;
    --header-height: 68px;
    height: calc(100svh - var(--header-height));
    min-height: 400px;
    @apply max-w-[100%];
    width: 100%;
    display: grid;
    grid-template-rows: 0 var(--inner-border) 1fr auto 1fr var(--inner-border) var(--outer-border);
    grid-template-columns: var(--outer-border) var(--inner-border) 1fr auto 1fr var(--inner-border) var(--outer-border);
    position: relative;
    overflow: hidden;
    transition: height 0.5s, width 0.5s;
}


.header-grid--open {
    height: calc(100svh - var(--header-height));
    transition: height 0.5s, max-width 0.5s;
    @apply max-w-[100%];
}

.header-grid--collapsed {
    height: calc(30svh - var(--header-height));
    transition: height 0.5s, max-width 0.5s;
    @apply max-w-6xl;
}

.glow-effect {
    position: absolute;
    width: 100%;
    height: 100%;
    aspect-ratio: 1;
    background: conic-gradient(
            from 0deg at 50% 50%,
            rgba(160, 236, 253, 1) 15deg,
            rgba(160, 236, 253, 0) 15deg,
            rgba(160, 236, 253, 0) 55deg,
            rgba(160, 236, 253, 0) 345deg,
            rgba(160, 236, 253, 1) 345deg
    );
    mix-blend-mode: screen;
    filter: blur(10px);
    transform-origin: center;
}

@media (max-width: 1366px), (hover: none), (pointer: coarse) {
    .glow-effect {
        animation: rotate-glow 8s linear infinite;
    }
}

.shiny-border {
    background-color: #262626;
    grid-area: 2 / 2 / 7 / 7;
    position: relative;
    overflow: hidden;
}

.header-grid > canvas {
    grid-area: 3 / 3 / 6 / 6;
    background-color: transparent;
    z-index: 3;
}

.header-text-content {
    grid-area: 4 / 3 / 5 / 6;
    z-index: 4;
}

@keyframes rotate-glow {
    from {
        transform: scale(6) rotate(0deg);
    }
    to {
        transform: scale(6) rotate(360deg);
    }
}

.slide-this {
    opacity: 1;
    transform: translateX(0);
}

@keyframes slideOutLeft {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(-100%);
        opacity: 0;
    }
}

@keyframes slideOutRight {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

@keyframes slideInLeft {
    from {
        transform: translateX(-100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes slideInRight {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}
</style>

<script>
import { pathConfigMap } from "../lib/constants/pages"
import { rotateCamera, updateColors } from "../lib/matrix-cover"

let isNavigating = false
let navigationDirection: "left" | "right"

function updateBorderGradient(rgbColor: string) {
  const glowEffect = document.querySelector(".glow-effect")
  if (glowEffect) {
    glowEffect.style.background = `
        conic-gradient(
          from 0deg at 50% 50%,
          rgba(${rgbColor}, 1) 15deg,
          rgba(${rgbColor}, 0) 15deg,
          rgba(${rgbColor}, 0) 55deg,
          rgba(${rgbColor}, 0) 345deg,
          rgba(${rgbColor}, 1) 345deg
        )
      `
  }
}

document.addEventListener("astro:before-preparation", (event: any) => {
  const getBasePath = (path: string) => {
    const firstSegment = path.split("/")[1]
    return firstSegment ? `/${firstSegment}` : "/"
  }

  const fromBasePath = getBasePath(event.from.pathname)
  const toBasePath = getBasePath(event.to.pathname)

  const fromConfig = pathConfigMap[fromBasePath] ?? pathConfigMap["/"]
  const toConfig = pathConfigMap[toBasePath] ?? pathConfigMap["/"]

  if (
    toConfig.index
    && toConfig.index !== fromConfig.index
    && fromBasePath !== toBasePath
  ) {
    isNavigating = true
    navigationDirection = toConfig.index > fromConfig.index ? "left" : "right"

    rotateCamera(navigationDirection)
    updateColors(toConfig.colors)
    updateBorderGradient(toConfig.colors.border)

    const slideThis = document.querySelector(".slide-this")
    if (slideThis) {
      slideThis.style.animation = `slideOut${
        navigationDirection.charAt(0).toUpperCase() + navigationDirection.slice(1)
      } 0.5s ease-out forwards`
    }
  } else {
    isNavigating = false
  }
})

document.addEventListener("astro:after-swap", () => {
  toggleCollapsed(window.location.pathname === "/")
  if (isNavigating) {
    const slideThis = document.querySelector(".slide-this")
    if (slideThis) {
      const slideInDirection = navigationDirection === "left" ? "Right" : "Left"
      slideThis.style.animation = `slideIn${slideInDirection} 0.5s ease-out forwards`
    }
  }
})

let headerGrid, glowEffect, mouseMoveHandler
let previousAngle = 0
let currentRotation = 0
let isTablet = false

function checkDeviceSize() {
  // Check for tablet/mobile sizes
  const isTablet = window.matchMedia("(max-width: 1366px)").matches

  const hasTouch = window.matchMedia("(hover: none)").matches
  const hasMouse = window.matchMedia("(pointer: fine)").matches

  return isTablet || hasTouch || !hasMouse
}

function initializeGlowEffect() {
  headerGrid = document.querySelector(".header-grid")
  glowEffect = document.querySelector(".glow-effect")
  checkDeviceSize()

  const currentPath = window.location.pathname
  const currentConfig = pathConfigMap[currentPath] ?? pathConfigMap["/"]
  updateBorderGradient(currentConfig.colors.border)

  if (headerGrid && glowEffect) {
    mouseMoveHandler = (e) => {
      if (isTablet) {
        return
      }

      const rect = headerGrid.getBoundingClientRect()
      const centerX = rect.left + rect.width / 2
      const centerY = rect.top + rect.height / 2

      const deltaX = e.clientX - centerX
      const deltaY = e.clientY - centerY
      const newAngle = Math.atan2(deltaY, deltaX) * (180 / Math.PI)

      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
      const maxDistance = Math.sqrt(
        Math.pow(Math.max(centerX, window.innerWidth - centerX), 4)
          + Math.pow(Math.max(centerY, window.innerHeight - centerY), 4),
      )

      const scale = Math.min(4, Math.max(5, (distance / maxDistance) * 6))

      let angleDiff = newAngle - previousAngle

      // Handle angle wraparound
      if (angleDiff > 180) {
        angleDiff -= 360
      } else if (angleDiff < -180) {
        angleDiff += 360
      }

      currentRotation += angleDiff
      previousAngle = newAngle

      // Update glow effect position and rotation
      glowEffect.style.transform = `scale(${scale}) rotate(${currentRotation + 90}deg)`
    }

    window.addEventListener("mousemove", mouseMoveHandler)
    window.addEventListener("resize", checkDeviceSize)
  }
}

function cleanup() {
  if (headerGrid && mouseMoveHandler) {
    headerGrid.removeEventListener("mousemove", mouseMoveHandler)
  }
  window.removeEventListener("resize", checkDeviceSize)
}

document.addEventListener("astro:page-load", () => {
  cleanup()
  initializeGlowEffect()
})

document.addEventListener("astro:before-preparation", (event) => {
  cleanup()
  toggleCollapsed(event.to.pathname === "/")
})

function toggleCollapsed(open) {
  headerGrid = document.querySelector(".header-grid")

  if (open) {
    headerGrid?.classList.remove("header-grid--collapsed")
    headerGrid?.classList.add("header-grid--open")
  } else {
    headerGrid?.classList.remove("header-grid--open")
    headerGrid?.classList.add("header-grid--collapsed")
  }
}

document.addEventListener(
  "astro:after-swap",
  () => toggleCollapsed(window.location.pathname === "/"),
)
</script>
